package com.kim.logs.controller;

import com.kim.logs.bean.OperatorLog;
import com.kim.logs.dto.EsSelectPageDTO;
import com.kim.logs.enums.LogsTypeEnums;
import com.kim.logs.utils.POJOConverter;
import com.kim.logs.utils.Result;
import com.kim.logs.vo.OperatorLogVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zxp.esclientrhl.repository.ElasticsearchTemplate;
import org.zxp.esclientrhl.repository.PageList;
import org.zxp.esclientrhl.repository.PageSortHighLight;
import org.zxp.esclientrhl.repository.Sort;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Project: SpringCloud6.2
 * @PackageName: com.kim.es.demo.controller
 * @FileName: EsController.java
 * @Description: The EsController is...
 * @Author: kimwu
 * @Time: 2020-09-11 15:15:16
 */
@RestController
@Slf4j
@RequestMapping(EsOperatorLogController.BASE_URL)
public class EsOperatorLogController {

    final static String BASE_URL = "/1.0/com/web/operatorLogs";

    @Autowired
    private ElasticsearchTemplate<OperatorLog, String> elasticsearchTemplate;

    /***
     * 支持分页、高亮、排序的查询
     * @param queryBuilder 查询条件
     * @param pageSortHighLight 封装了分页、排序、高亮的规格信息
     * @param clazz 泛型对应类类型
     * @return 泛型定义好的es索引结构实体类查询结果集合
     * @throws Exception
     */
    @PostMapping("/v1/esSelectPage")
    public Result pageList(@RequestBody EsSelectPageDTO dto) {
        String interfaceId = BASE_URL + "/v1/esSelectPage";
        //分页
        PageSortHighLight psh = new PageSortHighLight(dto.getPage(), dto.getPageSize());
        //排序字段，注意如果proposal_no是text类型会默认带有keyword性质，需要拼接.keyword
        String sorter = "createTime";
        Sort.Order order = new Sort.Order(SortOrder.DESC, sorter);
        psh.setSort(new Sort(order));
        PageList<OperatorLog> pageList = null;
        try {
            /**
             * 只有分页
             */
            if (!StringUtils.isNotBlank(dto.getStartTime()) && !StringUtils.isNotBlank(dto.getEndTime()) && dto.getType() == null) {
                // new MatchAllQueryBuilder() 参数： 查询所有
                pageList = elasticsearchTemplate.search(new MatchAllQueryBuilder(), psh, OperatorLog.class);
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                QueryBuilder queryBuilder = null;
                if (dto.getType() != null && StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
                    // 类型查询
                    QueryBuilder typeBuilder = QueryBuilders.termQuery("type", dto.getType());
                    // 时间段查询
                    QueryBuilder timeBuilder = QueryBuilders.rangeQuery("createTime")
                            .from(dateFormat.parse(dealTime(dto.getStartTime(), 1)).getTime())
                            .to(dateFormat.parse(dealTime(dto.getEndTime(), 2)).getTime());
                    queryBuilder = QueryBuilders.boolQuery().must(timeBuilder).must(typeBuilder);
                } else if (dto.getType() != null) {
                    // 类型查询
                    QueryBuilder typeBuilder = QueryBuilders.termQuery("type", dto.getType());
                    queryBuilder = QueryBuilders.boolQuery().must(typeBuilder);
                } else {
                    // 时间段查询
                    QueryBuilder timeBuilder = QueryBuilders.rangeQuery("createTime")
                            .from(dateFormat.parse(dealTime(dto.getStartTime(), 1)).getTime())
                            .to(dateFormat.parse(dealTime(dto.getEndTime(), 2)).getTime());
                    queryBuilder = QueryBuilders.boolQuery().must(timeBuilder);
                }
                pageList = elasticsearchTemplate.search(queryBuilder, psh, OperatorLog.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        pageList.getList().forEach(main2 ->
                log.info(main2.toString())
        );
        List<OperatorLogVO> operatorLogVOS = POJOConverter.copyList(pageList.getList(), OperatorLogVO.class);
        operatorLogVOS.forEach(o -> o.setType(LogsTypeEnums.getDesc(Integer.valueOf(o.getType()))));
        PageList<OperatorLogVO> operatorLogVOPageList = POJOConverter.copyEsPage(pageList, new PageList<OperatorLogVO>(), operatorLogVOS);
        return Result.success(operatorLogVOPageList);
    }

    private String dealTime(String time, Integer type) {
        //月头
        if (type == 1) {
            return time + " 00:00:00";
        } else if (type == 2) {
            return time + " 23:59:59";
        } else {
            throw new RuntimeException("type传值不正确");
        }
    }

}
